//
//  AppDelegate.m
//  eGifr
//
//  Created by Phien Tram on 8/4/13.
//  Copyright (c) 2013 eGiftr. All rights reserved.
//

#import "AppDelegate.h"
#import "UserDefaultHelper.h"
#import "ECSlidingViewController.h"
#import "ViewController.h"
#import "Constants.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

// Helper method to wrap logic for handling app links.
- (void)handleAppLink:(FBAccessTokenData *)appLinkToken {
    // Initialize a new blank session instance...
    FBSession *appLinkSession = [[FBSession alloc] initWithAppID:nil
                                                     permissions:nil
                                                 defaultAudience:FBSessionDefaultAudienceNone
                                                 urlSchemeSuffix:nil
                                              tokenCacheStrategy:[FBSessionTokenCachingStrategy nullCacheInstance] ];
    [FBSession setActiveSession:appLinkSession];
    // ... and open it from the App Link's Token.
    [appLinkSession openFromAccessTokenData:appLinkToken
                          completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
                              // Forward any errors to the FBLoginView delegate.
                              if (error) {
                                  NSLog(@"%@", error);
                              }
                          }];
}

// FBSample logic
// The native facebook application transitions back to an authenticating application when the user
// chooses to either log in, or cancel. The url passed to this method contains the token in the
// case of a successful login. By passing the url to the handleOpenURL method of FBAppCall the provided
// session object can parse the URL, and capture the token for use by the rest of the authenticating
// application; the return value of handleOpenURL indicates whether or not the URL was handled by the
// session object, and does not reflect whether or not the login was successful; the session object's
// state, as well as its arguments passed to the state completion handler indicate whether the login
// was successful; note that if the session is nil or closed when handleOpenURL is called, the expression
// will be boolean NO, meaning the URL was not handled by the authenticating application
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    // attempt to extract a token from the url
    return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication withSession:[FBSession activeSession] fallbackHandler:^(FBAppCall *call) {
        // Facebook SDK * App Linking *
        // For simplicity, this sample will ignore the link if the session is already
        // open but a more advanced app could support features like user switching.
        if (call.accessTokenData) {
            if ([FBSession activeSession].isOpen) {
                NSLog(@"INFO: Ignoring app link because current session is open.");
            }
            else {
                [self handleAppLink:call.accessTokenData];
            }
        }
    }];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    
    [self customizeAppearance];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultShowWelcomeTipsKey] == nil) {
        [UserDefaultHelper setShowWelcomeTips:YES];
    }
    self.myWishList = [UserDefaultHelper getMyWishList];
    
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.delegate = self;
    [self.locationManager startUpdatingLocation];
    
    return YES;
}
							
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    // We need to properly handle activation of the application with regards to SSO
    //  (e.g., returning from iOS 6.0 authorization dialog or from fast app switching).
    [FBAppCall handleDidBecomeActive];
    
    //show login view each time the app launches
    [[NSNotificationCenter defaultCenter] postNotificationName:kShouldShowLoginNotificationName object:nil];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[FBSession activeSession] close];
}

#pragma mark - Private methods

- (void)customizeAppearance
{
    [[UINavigationBar appearance] setTintColor:[UIColor colorWithRed:10.0f/255.0f green:186.0f/255.0f blue:181.0f/255.0f alpha:1.0f]];
//    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"bg_header"] forBarMetrics:UIBarMetricsDefault];
    
    // Customize the title text for *all* UINavigationBars
//    [[UINavigationBar appearance] setTitleTextAttributes:
//     [NSDictionary dictionaryWithObjectsAndKeys:
//      [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0], UITextAttributeTextColor,
//      [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8], UITextAttributeTextShadowColor,
//      [NSValue valueWithUIOffset:UIOffsetMake(0, 0)], UITextAttributeTextShadowOffset,
//      [UIFont fontWithName:@"Aller-Bold" size:18.0], UITextAttributeFont,
//      nil]];
    
}

#pragma mark - CLLocationManager delegate

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    self.currentLocation = newLocation;
//    NSLog(@"lat:%f long:%f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *newLocation = [locations lastObject];
//    if (newLocation.horizontalAccuracy > 0 && newLocation.horizontalAccuracy < 50) {
        self.currentLocation = newLocation;
//    }
}

#pragma mark - Public methods

- (void)startSpinner:(NSString *)text
{
    if (_spinner == nil) {
        _spinner = [[ActivityIndicatorView alloc] initWithHorizontalActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        
    }
    [_spinner setText:text];
    [self.window addSubview:_spinner];

    CGRect bnds = self.window.bounds;
    CGRect frame = _spinner.frame;
    frame.origin.x = (int)(bnds.size.width - _spinner.frame.size.width)/2;
    frame.origin.y = (int)(bnds.size.height - _spinner.frame.size.height)/2;
    _spinner.frame = frame;

    [_spinner startAnimating];

    // Disable this view and waiting purchasing finish.
    self.window.userInteractionEnabled = NO;
}

- (void)stopSpinner
{
    self.window.userInteractionEnabled = YES;
    
    if (_spinner) {
        [_spinner removeFromSuperview];
        [_spinner stopAnimating];
    }
}

@end
